package JUC.cas;

import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author mubei
 * @date 2021/11/23
 * @description
 */
public class ABA {

    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2021);
        System.out.println("捣乱的线程");
        System.out.println(atomicInteger.compareAndSet(2021, 2020));
        System.out.println(atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());

        System.out.println("期待的线程");
        System.out.println(atomicInteger.compareAndSet(2021, 2666));
        System.out.println(atomicInteger.get());
    }


    @Test()
    public void test1() {
        AtomicStampedReference<Integer> atomic = new AtomicStampedReference<>(2020, 1);

        new Thread(()->{
            int stamp = atomic.getStamp();
            System.out.println("a=>"+stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//          //  期待值  修改值   之前版本号   更新版本号
            System.out.println(atomic.compareAndSet(2020, 2021, atomic.getStamp(), atomic.getStamp() + 1));
            System.out.println("a2=>"+atomic.getStamp());
            atomic.compareAndSet(2021,2020,atomic.getStamp(), atomic.getStamp()+1);
            System.out.println("a3=>"+atomic.getStamp());

        },"a").start();
        new Thread(()->{
            int stamp = atomic.getStamp();
            System.out.println("b=>"+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomic.compareAndSet(2020,666,stamp,stamp+1);
            System.out.println("b1->"+atomic.getStamp());
        },"b").start();
    }
}
